var MaterialForm = function () {
  var template = /* html */ `
    <div class="material-form" v-loading.fullscreen.lock="loading">
      <el-form label-width="120px" size="medium">
        <el-form-item label="物料代码" v-if="type==='update'">
          <span>{{materialData.materialCode}}</span>
        </el-form-item>
        <el-form-item label="物料名称" required>
          <sys-autocomplete class="form-input" v-if="canUpdate&&isUpdateMaterialName" v-model="materialData.materialName" :options="materialNameList">
          </sys-autocomplete>
          <span v-else>{{materialData.materialName}}</span>
        </el-form-item>
        <el-form-item label="物料图片">
          <imgs-upload ref="materialImgsUpload" v-model="materialData.imgUrls" :limit="4" :auto-upload="false"></imgs-upload>
        </el-form-item>
        <el-form-item label="规格型号" required>
          <sys-autocomplete class="form-input" v-if="canUpdate" v-model="materialData.model" :options="modelList">
          </sys-autocomplete>
          <span v-else>{{materialData.model}}</span>
        </el-form-item>
        <el-form-item label="编号" required>
          <sys-autocomplete class="form-input" v-if="canUpdate" v-model="materialData.color" :options="colorList">
          </sys-autocomplete>
          <span v-else>{{materialData.color}}</span>
        </el-form-item>
        <el-form-item label="描述">
          <el-input class="form-input" v-if="canUpdate" v-model="materialData.colorDescription"></el-input>
          <span v-else>{{materialData.colorDescription}}</span>
        </el-form-item>
        <el-form-item label="物料部门">
          <el-select clearable filterable v-if="canUpdate" class="form-input" v-model="materialData.materialDept" value-key="materialDeptId">
            <el-option v-for="dept in deptList" :key="dept.materialDeptId" :value="dept" :label="dept.materialDeptName">
            </el-option>
          </el-select>
          <span v-else>{{materialData.materialDept!==''?materialData.materialDept.materialDeptName:''}}</span>
        </el-form-item>
        <el-form-item label="材质">
          <el-input class="form-input" v-model="materialData.material"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select class="form-input" v-model="materialData.status">
            <el-option value="使用"></el-option>
            <el-option value="禁用"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="默认仓库">
          <el-select class="form-input" v-if="canUpdate" v-model="materialData.defaultWarehouse" @change="warehouseChange">
            <el-option v-for="warehouse in warehouseList" :key="'warehouse_'+warehouse.value" :value="warehouse.value"
              :label="warehouse.label"></el-option>
          </el-select>
          <span v-else>{{i18n.getMsg('spotMaterial.defaultWarehouse.'+materialData.defaultWarehouse)}}</span>
        </el-form-item>
        <el-form-item label="物料类型">
          <el-select clearable filterable class="form-input" @change="resetMaterialName()" v-model="materialData.materialType">
            <el-option v-for="materialType in materialTypeList" :key="materialType" :value="materialType">
            </el-option>
          </el-select>
        </el-form-item>
        <template v-if="materialData.defaultWarehouse===1 && materialData.materialType==='镜片'">
          <el-form-item label="透光率">
            <el-input-number is-decimal-zero v-model="materialData.transmittance" class="form-input" :min="0" :max="100" :precision="2" :controls="false">
            </el-input-number>
          </el-form-item>
        </template>
        <el-form-item label="供应商" required>
          <template v-if="canUpdate">
            <el-select clearable filterable v-model="materialData.providerName" style="width:calc(100% - 120px)">
              <el-option v-for="providerName in providerNameList" :key="providerName" :value="providerName">
              </el-option>
            </el-select>
            <el-button type="primary" @click="addProvider">添加供应商</el-button>
          </template>
          <span v-else>{{materialData.providerName}}</span>
        </el-form-item>
        <el-form-item label="供方编号">
          <el-input class="form-input" v-model="materialData.providerNo"></el-input>
        </el-form-item>
        <el-form-item label="单位" required>
          <el-select filterable class="form-input" v-if="canUpdate" v-model="materialData.unit">
            <el-option v-for="unit in unitList" :key="unit" :value="unit"></el-option>
          </el-select>
          <span v-else>{{materialData.unit}}</span>
        </el-form-item>
        <el-form-item label="单价">
          <el-input-number class="form-input" :controls="false" v-model="materialData.unitPrice" :min="0" :max="999999" :precision="3">
          </el-input-number>
        </el-form-item>
        <el-form-item class="input-item" label="计价单位与生产单位是否相同">
          <span>{{materialData.unit==='付'?'相同':'不相同'}}</span>
        </el-form-item>
        <el-form-item label="采购周期">
          <el-input-number class="form-input" :controls="false" v-model="materialData.procurementCycles" :min="0" :max="365" :precision="0">
          </el-input-number>
        </el-form-item>
        <el-form-item label="库存上限">
          <el-input-number is-decimal-zero class="form-input" :controls="false" v-model="materialData.safetyStockMax" :min="0" :max="9999999999" :precision="2">
          </el-input-number>
        </el-form-item>
        <el-form-item label="库存下限">
          <el-input-number is-decimal-zero class="form-input" :controls="false" v-model="materialData.safetyStockMin" :min="0" :max="9999999999" :precision="2">
          </el-input-number>
        </el-form-item>
        <template v-if="type==='update'">
          <el-form-item label="创建人">
            <span>{{materialData.creater}}</span>
          </el-form-item>
          <el-form-item label="创建时间">
            <span>{{materialData.creationTime}}</span>
          </el-form-item>
          <el-form-item label="最后修改人">
            <span>{{materialData.lastModifier}}</span>
          </el-form-item>
          <el-form-item label="最后修改时间">
            <span>{{materialData.lastModifyTime}}</span>
          </el-form-item>
        </template>
      </el-form>

      <div style="text-align:center">
        <el-button size="medium" type="primary" @click="saveMaterial">
          <span v-if="type==='add'">保存</span>
          <span v-else>修改</span>
        </el-button>
      </div>

      <el-dialog append-to-body title="添加供应商" :visible.sync="openProvider" top="5vh">
        <div style="height: calc(85vh - 54px); overflow: auto">
          <customer-form v-if="openProvider" :customer-type="1" @save-success="addProviderSuccess">
          </customer-form>
        </div>
      </el-dialog>
    </div>
  `;

  return {
    props: {
      material: {
        type: Object,
        default: function () {
          return null;
        }
      },
      type: {
        type: String,
        required: true
      },
      dropdownOption: {
        type: Object,
        required: true
      }
    },

    mixins: [
      materialFormMixin('materialData')
    ],

    data: function () {
      var material = this.material;
      var materialData;
      if (material === null) {
        materialData = new SpotMaterialModel();
      } else {
        materialData = new SpotMaterialModel(material);
      }
      return {
        loading: false,
        materialData: materialData,
        materialNameList: [],
        modelList: [],
        colorList: [],
        deptList: [],
        materialTypeList: [],
        providerNameList: [],
        unitList: [],
        warehouseList: i18n.getDropDown('spotMaterial.defaultWarehouse', ['1', '2']),
        canUpdate: true,
        openProvider: false,
        i18n: i18n
      };
    },

    created: function () {
      this.loading = true;
      var self = this;
      Promise.all([
        this.initDropdownData(),
        this.checkCanUpdate()
      ]).then(function () {
        self.loading = false;
      }).catch(function () {
        self.loading = false;
      });
    },

    methods: {
      initDropdownData: function () {
        var self = this;
        return Promise.all([
          this.setDropdownList('materialNameList'),
          this.setDropdownList('modelList'),
          this.setDropdownList('colorList'),
          this.setDeptList(),
          this.setMaterialTypeList(),
          this.setDropdownList('providerNameList', 'customerName'),
          this.setDropdownList('unitList')
        ]).then(function (res) {
          self.resetMaterialName();
          return res;
        }).catch(function () {
          return null;
        });
      },

      checkCanUpdate: function () {
        if (this.type === 'add') {
          this.canUpdate = true;
          return Promise.resolve();
        }

        var materialCode = this.materialData.materialCode;
        if (materialCode === '') {
          this.canUpdate = false;
          return Promise.resolve();
        }

        var self = this;
        return ajaxRequest('basicData/queryMaterialCompanyIsUsed', {
          materialCode: materialCode
        }).then(function (isUsed) {
          var canUpdate = isUsed === 0;
          self.canUpdate = canUpdate;
          return canUpdate;
        });
      },

      setDropdownList: function (field, dataField) {
        var dropdownList = this.dropdownOption[field];
        if (dropdownList !== undefined) {
          this[field] = dropdownList;
          return Promise.resolve(dropdownList);
        }

        var url;
        var postData = {};
        switch (field) {
          case 'materialNameList':
            url = 'basicData/getCompanyMaterialName';
            break;
          case 'modelList':
            url = 'basicData/getCompanyModel';
            break;
          case 'colorList':
            url = 'basicData/getCompanyColor';
            break;
          case 'providerNameList':
            url = 'basicData/getCustomerName';
            postData = {
              view: 1
            };
            break;
          case 'unitList':
            url = 'basicData/getCompanyUnit';
        }

        var self = this;
        return ajaxRequest(url, postData).then(function (dropdownList) {
          var dropdownData = [];
          for (var i = 0; i < dropdownList.length; i++) {
            var dropdown = dropdownList[i];
            var value = dataField ? dropdown[dataField] : dropdown;
            if (!SysUtil.isEmpty(value)) {
              dropdownData.push(value);
            }
          }
          dropdownData = _.uniq(dropdownData);
          if (field === 'unitList') {
            dropdownData = _.orderBy(dropdownData, [function (value) {
              if (['条', '付'].indexOf(value) !== -1) {
                return 0;
              }
              return 1;
            }], ['asc']);
          }
          self[field] = dropdownData;
          self.dropdownOption[field] = dropdownData;
          return dropdownData;
        });
      },

      setDeptList: function () {
        var deptList = this.dropdownOption.deptList;
        if (deptList !== undefined) {
          this.deptList = deptList;
          return Promise.resolve(deptList);
        }

        var self = this;
        return ajaxRequest('basicData/getDeptName', {
          view: 1
        }).then(function (deptList) {
          deptList = _.map(deptList, function (dept) {
            return {
              materialDeptId: dept.id,
              materialDeptName: dept.deptName
            };
          });
          self.deptList = deptList;
          self.dropdownOption.deptList = deptList;
          return deptList;
        });
      },

      setMaterialTypeList: function () {
        var materialData = this.materialData;
        var self = this;
        return ajaxRequest("basicData/getRowMaterialType", {
          defaultWarehouse: materialData.defaultWarehouse
        }).then(function (materialTypeList) {
          self.materialTypeList = materialTypeList;
          return materialTypeList;
        });
      },

      warehouseChange: function () {
        this.loading = true;
        var self = this;
        this.setMaterialTypeList().then(function (materialTypeList) {
          var materialData = self.materialData;
          if (materialData.materialType !== '' && materialTypeList.indexOf(materialData.materialType) === -1) {
            materialData.materialType = '';
          }
          self.resetMaterialName();
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        });
      },

      addProvider: function () {
        this.openProvider = true;
      },

      addProviderSuccess: function (provider) {
        this.openProvider = false;
        delete this.dropdownOption.providerNameList;
        this.loading = true;
        var self = this;
        this.setDropdownList('providerNameList', 'customerName').then(function () {
          self.materialData.providerName = provider.customerName;
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        });
      },

      saveMaterial: function () {
        var materialData = this.materialData;
        var code = materialData.checkValid();
        if (code !== '') {
          this.$alert(i18n.getMsg(`spotMaterial.error.${code}`), '信息');
          return;
        }

        var self = this;
        this.loading = true;
        this.$refs['materialImgsUpload'].submit().then(function () {
          return self.toSaveMaterial().then(function () {
            self.loading = false;
          });
        }).catch(function () {
          self.loading = false;
          self.$alert('物料图片上传失败', '信息');
        });
      },

      toSaveMaterial: function () {
        var materialData = this.materialData;
        var type = this.type;
        var postData = materialData.getObject(type);
        var url = type === 'add' ? 'basicData/insertCompanyMaterial' : 'basicData/updateCompanyMaterial';

        var self = this;
        return ajaxRequest(url, postData).then(function (msg) {
          msg = type === 'add' ? '现货保存成功' : '现货修改成功';
          self.$alert(msg, '信息', {
            callback: function () {
              self.$emit('save-success');
            }
          });
          self.clearDropdownOption(postData);
          return msg;
        }).catch(function () {
          return '';
        });
      },

      clearDropdownOption: function (postData) {
        var fields = ['materialName', 'model', 'color'];
        var dropdownOption = this.dropdownOption;
        for (var i = 0; i < fields.length; i++) {
          var field = fields[i];
          var value = postData[field];
          var dropdownList = dropdownOption[`${field}List`];
          if (dropdownList.indexOf(value) === -1) {
            delete dropdownOption[`${field}List`];
          }
        }
      }
    },

    components: {
      SysAutocomplete: SysAutocomplete,
      ImgsUpload: ImgsUpload,
      CustomerForm: CustomerForm
    },

    template: template
  };
}();
